﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;

namespace this_is_my_zone
{
    public partial class ImageResizer : System.Web.UI.Page
    {        
        protected void Page_Load(object sender, EventArgs e)
        {
            ImageCodecInfo[] imgCodes = ImageCodecInfo.GetImageEncoders();
            EncoderParameters imgEnc = new EncoderParameters();            
        }

        private void ShowAlert(string Message)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "alert('>>>>>> " + Message + " <<<<<<');", true);            
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (imgUpload.HasFile)
                {
                    bool isImageFile = imgUpload.PostedFile.ContentType.Split('/')[0].Equals("image");
                    if (isImageFile)
                    {
                        var Width = Convert.ToInt32(txtWidth.Text);
                        var Height = Convert.ToInt32(txtHeight.Text);
                        Resize(Width, Height, imgUpload.PostedFile.InputStream);
                    }
                    else
                    {
                        ShowAlert("Only Image file are allowed");
                        return;
                    }
                }
                else
                {
                    ShowAlert("Please Select a File");
                    imgUpload.Focus();
                    return;
                }
            }
            catch (Exception ex) { }
        }

        private void Resize(int Width, int Height, Stream imgStream)
        {            
            System.Drawing.Image img = System.Drawing.Image.FromStream(imgStream);
            System.Drawing.Image resizedImg = img.GetThumbnailImage(Width, Height, null, IntPtr.Zero);            
            Response.ClearHeaders();
            Response.ContentType = "image/png";
            Response.AddHeader("Content-Disposition", "attachment; filename=test.png");
            resizedImg.Save(Response.OutputStream, ImageFormat.Png);
        }
    }
}